package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.atguigu.tingshu.user.config.properties.WxAutoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

@Configuration
@EnableConfigurationProperties(WxAutoProperties.class)
public class WxAutoConfiguration {

    @Autowired
    private WxAutoProperties wxAutoProperties;

    // 微信客户端
    @Bean
    public WxMaService wxMaService() {
        WxMaService wxMaService = new WxMaServiceImpl();
        WxMaDefaultConfigImpl wxMaConfig = new WxMaDefaultConfigImpl();
        wxMaConfig.setAppid(wxAutoProperties.getAppId());
        wxMaConfig.setSecret(wxAutoProperties.getAppSecret());
        wxMaService.setWxMaConfig(wxMaConfig);
        return wxMaService;
    }

    // 定义一个RSA签名的Bean对象
    @Bean
    public RsaSigner RsaSigner() {
        // 从配置文件中读取
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        // 创建一个工厂对象 读取密钥文件
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
        return new RsaSigner(aPrivate);
    }
}
